#!/usr/bin/env python3

import os

import common

class QemuComponent(common.Component):
    def add_parser_arguments(self, parser):
        parser.add_argument(
            '--userland',
            default=False,
            action='store_true',
            help='Build QEMU user mode instead of system.',
        )
        parser.add_argument(
            'extra_config_args',
            default=[],
            metavar='extra-config-args',
            nargs='*'
        )

    def do_build(self, args):
        build_dir = self.get_build_dir(args)
        os.makedirs(build_dir, exist_ok=True)
        if args.verbose:
            verbose = ['V=1']
        else:
            verbose = []
        if args.userland:
            target_list = '{}-linux-user'.format(args.arch)
        else:
            target_list = '{}-softmmu'.format(args.arch)
        common.run_cmd(
            [
                os.path.join(common.qemu_src_dir, 'configure'),
                '--enable-debug',
                '--enable-trace-backends=simple',
                '--target-list={}'.format(target_list),
                '--enable-sdl',
                '--with-sdlabi=2.0',
            ] +
            args.extra_config_args,
            extra_paths=[common.ccache_dir],
            cwd=build_dir
        )
        common.run_cmd(
            (
                [
                    'make',
                    '-j', str(args.nproc),

                ] +
                verbose
            ),
            cwd=build_dir,
            extra_paths=[common.ccache_dir],
        )

    def get_build_dir(self, args):
        return common.qemu_build_dir

if __name__ == '__main__':
    QemuComponent().build()
